<?php
class CommonAction extends Action {
	
	function _initialize() {
		import('@.ORG.Util.Cookie');
				if (! $_SESSION [C ( 'USER_AUTH_KEY' )]) {
					if ($this->isAjax()){ // zhanghuihua@msn.com
						$this->ajaxReturn(true, "", 301);
					} else {
						//跳转到认证网关
						redirect (  C ( 'USER_AUTH_GATEWAY' ) );
					}
				}
			if (C ( 'GUEST_AUTH_ON' )) {
				$this->assign ( 'jumpUrl',  C ( 'USER_AUTH_GATEWAY' ) );
			}
	}
	public function Successs($message,$jumpUrl='',$status='1',$waitSecond='3'){
		if($jumpUrl){
			$this->assign('jumpUrl',$jumpUrl);//地址
		}else{
		$this->assign('jumpUrl','-1');
		}
		$this->assign('status',$status);   // 状态
		$this->assign('message',$message);// 提示信息
		$this->assign('waitSecond',$waitSecond);//跳转秒数
		$this->assign('waitSeconds',$waitSecond*1000);//跳转秒数
	        
		if($status==1)
		{
			$this->assign('msgTitle','成功');  
		}
		else 
		{
			$this->assign('msgTitle','失败');  
		}
		$this -> display('Public:success');
		exit();
	}
	
	
	//提示 tip 0弹出提示 1不弹出
	public function Verifylogin($tip=0)
	{
		if(session('adminid') AND session('username') AND session('nickname') AND session('password')){
			$where['username'] = session('username');
			$where['nickname'] = session('nickname');
			$where['id'] = session('adminid');
			$users = M("web_user");
			$user = $users->where($where)->field('password,verify')->find();
			if(sha1($user['password'].$user['verify']) == session('password')){
				session('adminid','');
				session('username','');
				session('nickname','');
				session('password','');
				return session('adminid');
			}else{
				if($tip==1){
					return -9;
				}else{
					$this->Successs('登录验证错误！','/Home/index.php/User/Adminlogin',2);
				}
			}

		}else{
			if($tip==1){
				return -9;
			}else{
				$this->Successs('登录验证错误！','/Home/index.php/User/Adminlogin',2);
			}
		}		
		
	}
	
	
	public function menus() {
        if(isset($_SESSION[C('USER_AUTH_KEY')])) {
            //显示菜单项
            $menu  = array();
            if(isset($_SESSION['menus'.$_SESSION[C('USER_AUTH_KEY')]])) {

                //如果已经缓存，直接读取缓存
                $menu   =   $_SESSION['menus'.$_SESSION[C('USER_AUTH_KEY')]];
            }else {
          	  return $this->smenu();
			}
		}
	}
	
	
	public function smenu()
	{
            	$power = M("web_power");
				$id	=	$this->Verifylogin();
                $list	=	$power->table('jym_web_power as a,jym_web_role_power as b')->where('a.id=b.power_id AND b.role_id='.$id.' AND a.is_show=1 AND b.status=1 AND a.is_menu=1')->field('a.id,a.name,a.parent,a.module,a.action,a.url')->order('a.sort asc')->select();
                $accessList = $_SESSION['_ACCESS_LIST'];
                //print_r($list);
                foreach($list as $key=>$module) {
                        if($module['parent']==0){
                        	$menu[$module['id']]['name'] = $module['name'];
                        	$menu[$module['id']]['module'] = $module['module'];
                        	$menu[$module['id']]['action'] = $module['action'];
                        	$menua[] = $module['id'];
                        	unset($list[$key]);
                        }
                }
                unset($module);
                //print_r($menua);
                foreach($list as $keys=>$module) {
                	foreach($menua as $key=>$modules) {
                		if($modules == $module['parent']){
	                        $menu[$module['parent']]['expand'][$module['id']]['name'] = $module['name'];
	                        $menu[$module['parent']]['expand'][$module['id']]['module'] = $module['module'];
	                        $menu[$module['parent']]['expand'][$module['id']]['action'] = $module['action'];
	                        $menu[$module['parent']]['expand'][$module['id']]['url'] = $module['url'];
	                        $menu[$module['parent']]['expand'][$module['id']]['id'] = $module['id'];
	                        $menu[$module['parent']]['sl']++;
                			$menub[$module['id']]['id'] = $module['id'];
                			$menub[$module['id']]['parent'] = $module['parent'];
	                        unset($list[$keys]);
                		}
                	}
                }
     			unset($module);
     			unset($modules);
                foreach($list as $key=>$module) {
                	foreach($menub as $key=>$moduless) {
                		if($moduless['id'] == $module['parent']){
	                        $menu[$moduless['parent']]['expand'][$moduless['id']]['expand'][$module['id']]['name'] = $module['name'];
	                        $menu[$moduless['parent']]['expand'][$moduless['id']]['expand'][$module['id']]['module'] = $module['module'];
	                        $menu[$moduless['parent']]['expand'][$moduless['id']]['expand'][$module['id']]['action'] = $module['action'];
	                        $menu[$moduless['parent']]['expand'][$moduless['id']]['expand'][$module['id']]['url'] = $module['url'];
	                        $menu[$moduless['parent']]['expand'][$moduless['id']]['expand'][$module['id']]['id'] = $module['id'];
	                        $menu[$moduless['parent']]['sl']++;
                		}
                	}
                }
                //缓存菜单访问
                $_SESSION['menus'.$_SESSION[C('USER_AUTH_KEY')]]	=	$menu;
                //print_r($menu);
                //exit();
                return $menu;
		
	}
	
	
	
	public	function fj_sjzf($sing=1,$type=0)
	{
		$asc = '';
		for($sings=1;$sings<=$sing;$sings++){
			if($type==1){$number = 0;}elseif($type==2){$number = 1;}elseif($type==3){$number = 2;}else{$number=rand(0,2);}
			switch($number)
			{
				case	0:	$rand_number=rand(48,57);break;//数字
				case	1:	$rand_number=rand(65,90);break;//大写字母
				case	2:	$rand_number=rand(97,122);break;//小写字母
			}
				$asc	.=sprintf("%c",$rand_number);
		}
		return $asc;
	}
	
	public function fj_url($url='')
	{
		if($url!=''){
		}else{
			$url = $_SERVER['HTTP_HOST'];
		}
		$url = ereg_replace('http://','',$url);
		$url = ereg_replace('\.com','',$url);
		$url = ereg_replace('www\.','',$url);
		return $url;
	}
	
	//==================================获取用户ip开始 无法检测代理服务器===================================
	public	function fj_getIP()
	{
	    static $realip;
	    if (isset($_SERVER)){
	        if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])){
	            $realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
	        } else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
	            $realip = $_SERVER["HTTP_CLIENT_IP"];
	        } else {
	            $realip = $_SERVER["REMOTE_ADDR"];
	        }
	    } else {
	        if (getenv("HTTP_X_FORWARDED_FOR")){
	            $realip = getenv("HTTP_X_FORWARDED_FOR");
	        } else if (getenv("HTTP_CLIENT_IP")) {
	            $realip = getenv("HTTP_CLIENT_IP");
	        } else {
	            $realip = getenv("REMOTE_ADDR");
	        }
	    }

	    return $realip;
	}
//==================================获取用户ip结束 无法检测代理服务器===================================

	/**
    +----------------------------------------------------------
    * 管理员操作日志
    +----------------------------------------------------------
    */
	public function admin_log($log_cat='',$log_obj='',$log_con='',$state=0) {
		$this->admin_log = M('admin_log');
		$adminid = $this->Verifylogin(1);
		$adminname = session('username');
	    $data = array (
		    'u_id'			   => $adminid,
	    	'log_user'       => $adminname,
	  		'table_name'  => $log_obj,
		    'log_info'		   => $log_cat,
		    'details'		   => $log_con,
	 	    'log_ip'		   => $this->fj_getIP(),
		    'log_time'	   => time(),
			'status'			   => $state,
		);
		$insertId=$this->admin_log->add($data);
	}

	public function index() {
		//列表过滤器，生成查询Map对象
		$map = $this->_search ();
		if (method_exists ( $this, '_filter' )) {
			$this->_filter ( $map );
		}
		$name=$this->getActionName();
		$model = D ($name);
		if (! empty ( $model )) {
			$this->_list ( $model, $map );
		}
		$this->display ();
		return;
	}
	
	
	/**
     +----------------------------------------------------------
	 * 根据表单生成查询条件
	 * 进行列表过滤
     +----------------------------------------------------------
	 * @access protected
     +----------------------------------------------------------
	 * @param string $name 数据对象名称
     +----------------------------------------------------------
	 * @return HashMap
     +----------------------------------------------------------
	 * @throws ThinkExecption
     +----------------------------------------------------------
	 */
	protected function _search($name = '') {
		//生成查询条件
		if (empty ( $name )) {
			$name = $this->getActionName();
		}
        $name = $this->getActionName();
		$model = D ( $name );
		$map = array ();
		foreach ( $model->getDbFields () as $key => $val ) {
			if (isset ( $_REQUEST [$val] ) && $_REQUEST [$val] != '') {
				$map [$val] = $_REQUEST [$val];
			}
		}
		return $map;

	}
	
	/**
     +----------------------------------------------------------
	 * 根据表单生成查询条件
	 * 进行列表过滤
     +----------------------------------------------------------
	 * @access protected
     +----------------------------------------------------------
	 * @param Model $model 数据对象
	 * @param HashMap $map 过滤条件
	 * @param string $sortBy 排序
	 * @param boolean $asc 是否正序
     +----------------------------------------------------------
	 * @return void
     +----------------------------------------------------------
	 * @throws ThinkExecption
     +----------------------------------------------------------
	 */
	protected function _list($model, $map, $sortBy = '', $asc = false) {
		//排序字段 默认为主键名
		if (!empty ( $_REQUEST ['_order'] )) {
			$order = $_REQUEST ['_order'];
		} else {
			$order = ! empty ( $sortBy ) ? $sortBy : $model->getPk ();
		}
		//排序方式默认按照倒序排列
		//接受 sost参数 0 表示倒序 非0都 表示正序
		if (isset ( $_REQUEST ['_sort'] )) {
//			$sort = $_REQUEST ['_sort'] ? 'asc' : 'desc';
			$sort = $_REQUEST ['_sort'] == 'asc' ? 'asc' : 'desc'; //zhanghuihua@msn.com
		} else {
			$sort = $asc ? 'asc' : 'desc';
		}
		//取得满足条件的记录数
		$count = $model->where ( $map )->count ( 'id' );
		if ($count > 0) {
			import ( "@.ORG.Util.Page" );
			//创建分页对象
			if (! empty ( $_REQUEST ['listRows'] )) {
				$listRows = $_REQUEST ['listRows'];
			} else {
				$listRows = '';
			}
			$p = new Page ( $count, $listRows );
			//分页查询数据
			$voList = $model->where($map)->order( "`" . $order . "` " . $sort)->limit($p->firstRow . ',' . $p->listRows)->select ( );

			//echo $model->getlastsql();
			//分页跳转的时候保证查询条件
			foreach ( $map as $key => $val ) {
				if (! is_array ( $val )) {
					$p->parameter .= "$key=" . urlencode ( $val ) . "&";
				}
			}
			//分页显示
			$page = $p->show ();
			//列表排序显示
			$sortImg = $sort; //排序图标
			$sortAlt = $sort == 'desc' ? '升序排列' : '倒序排列'; //排序提示
			$sort = $sort == 'desc' ? 1 : 0; //排序方式
			//模板赋值显示
			$this->assign ( 'list', $voList );
			$this->assign ( 'sort', $sort );
			$this->assign ( 'order', $order );
			$this->assign ( 'sortImg', $sortImg );
			$this->assign ( 'sortType', $sortAlt );
			$this->assign ( "page", $page );
		}
		
		//zhanghuihua@msn.com
		$this->assign ( 'totalCount', $count );
		$this->assign ( 'numPerPage', $p->listRows );
		$this->assign ( 'currentPage', !empty($_REQUEST[C('VAR_PAGE')])?$_REQUEST[C('VAR_PAGE')]:1);
			
		Cookie( '_currentUrl_', __SELF__ );
		return;
	}
	
	
	/**
     +----------------------------------------------------------
	 * 取得操作成功后要返回的URL地址
	 * 默认返回当前模块的默认操作
	 * 可以在action控制器中重载
     +----------------------------------------------------------
	 * @access public
     +----------------------------------------------------------
	 * @return string
     +----------------------------------------------------------
	 * @throws ThinkExecption
     +----------------------------------------------------------
	 */
	function getReturnUrl() {
		return __URL__ . '?' . C ( 'VAR_MODULE' ) . '=' . MODULE_NAME . '&' . C ( 'VAR_ACTION' ) . '=' . C ( 'DEFAULT_ACTION' );
	}
	

	function saveSort() {
		$seqNoList = $_POST ['seqNoList'];
		if (! empty ( $seqNoList )) {
			//更新数据对象
		$name=$this->getActionName();
		$model = D ($name);
			$col = explode ( ',', $seqNoList );
			//启动事务
			$model->startTrans ();
			foreach ( $col as $val ) {
				$val = explode ( ':', $val );
				$model->id = $val [0];
				$model->sort = $val [1];
				$result = $model->save ();
				if (! $result) {
					break;
				}
			}
			//提交事务
			$model->commit ();
			if ($result!==false) {
				//采用普通方式跳转刷新页面
				$this->success ( '更新成功' );
			} else {
				$this->error ( $model->getError () );
			}
		}
	}

}
?>